﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TLECDataLayer;

namespace EventManager
{
    public partial class CategoriesForm : Form
    {
        private Category selectedCategory;

        public CategoriesForm()
        {
            InitializeComponent();
            WinLoad();
        }

        private void WinLoad()
        {
            this.categoryBindingSource.DataSource = Categories.GetAllCategories();
        }

        private void categoriesDGV_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != this.categoriesDGV.Rows.Count - 1 && e.RowIndex != -1)
            {
                selectedCategory = Categories.GetCategoryById(((Category)this.categoriesDGV.Rows[e.RowIndex].DataBoundItem).CategoryId);
                this.catNameTxt.Text = selectedCategory.CategoryType;
            }
            else
            {
                this.catNameTxt.Text = "";
                selectedCategory = null;
            }
        }

        private void saveBtn_Click(object sender, EventArgs e)
        {
            if (selectedCategory != null && !string.IsNullOrEmpty(this.catNameTxt.Text))
            {
                Categories.UpdateCategory(selectedCategory.CategoryId, this.catNameTxt.Text);
                MessageBox.Show("Changes have been saved");
            }
            else if (!string.IsNullOrEmpty(this.catNameTxt.Text))
            {
                Categories.CreateCategory(this.catNameTxt.Text);
                MessageBox.Show("New category has been added");
            }
            WinLoad();
        }

        private void deleteBtn_Click(object sender, EventArgs e)
        {
            if (selectedCategory != null)
            {

                if (TLECDataLayer.Events.GetAllUpcomingEventsByCategory(selectedCategory.CategoryId).Count() == 0)
                {
                    Categories.DeleteCategory(selectedCategory.CategoryId);
                    MessageBox.Show("The selected item has been deleted");
                }
                else
                {
                    MessageBox.Show("You can not delete this category because there are events with it!");
                }
            }
            else
            {
                MessageBox.Show("Select some item first.");
            }
            WinLoad();
        }
    }
}
